import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Req,
  UseGuards,
  Query,
} from '@nestjs/common';
import { PostsService } from './posts.service';
import { CreatePostDto } from './dto/create-post.dto';
import { UpdatePostDto } from './dto/update-post.dto';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { Roles, RolesGuard } from '../auth/role.guard';
import { QueryContentDto, searchDto } from './dto/find-post.dto';

@ApiTags('文章')
@Controller('posts')
export class PostsController {
  constructor(private readonly postsService: PostsService) {}

  @ApiOperation({ summary: '创建文章' })
  @ApiBearerAuth()
  @Post()
  @Roles('admin', 'root')
  @UseGuards(AuthGuard('jwt'), RolesGuard)
  async create(@Body() post: CreatePostDto, @Req() req) {
    return await this.postsService.create(req.user, post);
  }

  @ApiOperation({ summary: '获取文章列表' })
  @Get()
  findAll(@Query() query: QueryContentDto) {
    return this.postsService.findAll(query);
  }

  @ApiOperation({ summary: '获取档案' })
  @Get('/getArchive')
  getArchive() {
    return this.postsService.getArchive();
  }

  @ApiOperation({ summary: '按条件查询' })
  @Get('/search')
  searchArticles(@Query() query: searchDto) {
    return this.postsService.search(query);
  }

  @ApiOperation({ summary: '获取指定文章' })
  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.postsService.findById(id);
  }

  @ApiOperation({ summary: '获取指定文章(管理员后台查看，不计入浏览量)' })
  @Get('/findByIdAdmin/:id')
  @ApiBearerAuth()
  @Roles('admin', 'root')
  @UseGuards(AuthGuard('jwt'), RolesGuard)
  findByIdAdmin(@Param('id') id: string) {
    return this.postsService.findByIdAdmin(id);
  }

  @ApiOperation({ summary: '更新指定文章' })
  @Patch(':id')
  @ApiBearerAuth()
  @Roles('admin', 'root')
  @UseGuards(AuthGuard('jwt'), RolesGuard)
  update(
    @Param('id') id: string,
    @Body() updatePostDto: UpdatePostDto,
    @Req() req,
  ) {
    return this.postsService.update(req.user, id, updatePostDto);
  }

  @ApiOperation({ summary: '删除指定文章' })
  @ApiBearerAuth()
  @Roles('admin', 'root')
  @UseGuards(AuthGuard('jwt'), RolesGuard)
  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.postsService.remove(id);
  }
}
